package com.google.code.netbuilder.dal.entities;

import java.util.List;
import javax.persistence.*;
import javax.xml.bind.annotation.*;

@XmlRootElement(name = "cable")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity
@Table(name = "cable")
@SequenceGenerator(sequenceName = "cable_seq", name = "cable_seq", initialValue = 1, allocationSize = 100)
public class Cable extends ManagedObject {
    
	private static final long serialVersionUID = 3685524779486444294L;

	@XmlElementWrapper(name = "wires")
    @XmlElement(name = "wire")
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(table = "wire", name = "cable_id")
    private List<Wire> cableWires;
    
    @XmlAttribute(name = "type")
    private String type;

    public List<Wire> getCableWires() {
        return cableWires;
    }

    public void setCableWires(List<Wire> cableWires) {
        this.cableWires = cableWires;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
    
    @Override
    public boolean equals(Object ob)
    {
        if(ob == null)
        {
            return false;
        }
        if(!(ob instanceof Cable))
        {
            return false;
        }
        Cable castedOb = (Cable) ob;
        return super.equals(ob) && 
              (type != null ? type.equals(castedOb.getType()) : castedOb.getType() == null) &&
              (cableWires != null ? cableWires.equals(castedOb.getCableWires()) : cableWires == castedOb.getCableWires());
    }

    @Override
    public String toString() {
        return "Cable{" + super.toString() + ", cableWires=" + cableWires + ", type=" + type + '}';
    }
    
    public int getNumOfFreeWires() {
        
        int counter = 0;
        
        for(Wire w : cableWires ) {
            
            if(w.getFromPort() == null && w.getToPort() == null) {
                
                counter++;
            }
        }
        
        return counter;
    }
}
